import os
import pdb
import numpy as np
import cv2
import shutil

classes = ['aeroplane', 'bicycle', 'boat', 'bottle', 'car', 'cat', 'chair', 'diningtable', 'dog',
                         'horse', 'person', 'pottedplant', 'sheep', 'train', 'tvmonitor', 'bird', 'bus', 'cow',
                         'motorbike', 'sofa']

boxes_file = 'data/VOCdevkit2007/results/VOC2007/Main/comp4_det_test_' + classes[10] + '.txt'

boxes = []
with open(boxes_file, 'r') as f:
    for line in f.readlines():
        boxes.append(line.strip('\n').split(' '))

img_name      = [x[0] for x in boxes]
boxes_score   = [float(x[1]) for x in boxes]
boxes_loc     = [x[2:] for x in boxes]


save_dir = 'image_results/'

if os.path.exists(save_dir):
    shutil.rmtree(save_dir)

os.mkdir(save_dir)

print('the mean of score is : ', np.mean(boxes_score))
print('the std of score is : ', np.std(boxes_score))
print('the median of score is : ', np.median(boxes_score))

for img_num in range(5):
    img_path = 'data/VOCdevkit2007/VOC2007/JPEGImages/%s.jpg' % (img_name[img_num])
    result_path = os.path.join(save_dir, img_name[img_num] + '_result.jpg')
    
    if os.path.exists(result_path):
        img = cv2.imread(result_path)
    else:
        img = cv2.imread(img_path)
    
    score = boxes_score[img_num]
    xmin = int(float(boxes_loc[img_num][0]))
    ymin = int(float(boxes_loc[img_num][1]))
    xmax = int(float(boxes_loc[img_num][2]))
    ymax = int(float(boxes_loc[img_num][3]))
    
    cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)
    cv2.rectangle(img, (xmin, ymax - 15), (xmax, ymax), (0, 255, 0), cv2.FILLED)
    cv2.putText(img, classes[10] + ' : ' + str(score)[0:3], (xmin + 6, ymax - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), thickness=2) # the first split
    
    cv2.imwrite(result_path, img)
    
    